import re
import json
import math
import time
import random
from urllib.parse import urlencode
from weibosender.http_utils.http_request import HttpRequest
from weibosender.dal.receivers_dal import ReceiversDAL


class Weibo:
    _pattern_st = re.compile(r'"st":"(?P<st>.+?)"')

    _url_login = 'https://passport.weibo.cn/sso/login'
    _url_send_msg = 'http://m.weibo.cn/msgDeal/sendMsg?'
    _url_chat_page = 'http://m.weibo.cn/msg/chat?uid=%s'
    _url_user = 'http://m.weibo.cn/container/getIndex?containerid=%s'

    _headers = [
        ('Content-Type', 'application/x-www-form-urlencoded'),
        ('Origin', 'http://weibo.cn'),
        ('Accept-Encoding', 'gzip, deflate'),
        ('User-Agent',
         'Mozilla/5.0 (iPhone; CPU iPhone OS 10_1_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0 Mobile/14B100 Safari/602.1'),
        ("Connection", "keep-alive"),
        ("Accept", "*/*"),
        ("Referer", "http://weibo.cn"),
        ("Accept-Language", "zh-cn")
    ]

    '''
    登录
    '''
    @staticmethod
    def login(user):
        if user is None:
            print('登录失败：用户信息不能为空')
            return None

        data = {
            'username': user[0],
            'password': user[1],
            'savestate': 1,
            'ec': 0,
            'entry': 'mweibo'
        }
        data = urlencode(data)
        data = data.encode('utf-8')
        return HttpRequest.post(Weibo._url_login, data, Weibo._headers)

    '''
    发送私信
    '''
    @staticmethod
    def send_msg(sender, msg, callback=None):
        if msg is None:
            print('私信发送失败 > 信息内容不能为空')
            return None
        cookies = sender['cookies']
        # st = sender['st']

        receiver_uid = msg['receiver_uid']
        content = msg['content']
        st = Weibo._get_st(receiver_uid, cookies)
        if not st and not sender['st']:
            print('发送私信失败 > st请求失败')
            return None

        if st and not sender['st']:
            sender['st'] = st
        #     st = Weibo._get_st(receiver_uid, cookies)
        #     if not st: return None
        #     sender['st'] = st
        #     if callback: callback(sender)
        st = sender['st']
        data = {
            'fileId': 'null',
            'uid': receiver_uid,
            'content': content,
            'st': st
        }
        data = urlencode(data)
        data = data.encode('utf-8')
        return HttpRequest.post(Weibo._url_send_msg, data, Weibo._headers, cookies)
    '''
    发送消息时，获取st字段值
    '''
    @staticmethod
    def _get_st(uid, cookies):
        url = Weibo._url_chat_page % uid
        the_page = HttpRequest.get(url, Weibo._headers, cookies)
        if not the_page: return None
        search_obj = Weibo._pattern_st.search(the_page)
        st = ''
        if search_obj:
            st = search_obj.group('st')
        return st

    '''
    获取用户数据
    '''
    @staticmethod
    def get_user(tag_id, page):
        param_page = page > 1 and '&page=%s' % page or ''
        url = Weibo._url_user % tag_id + param_page

        return HttpRequest.get(url, Weibo._headers)